<!-- 股票列表 -->
<template>
  <div class="DealerInfoStyle">
    <div class="cardAdmin">
      <div class="formContainer">
        <div style="position: absolute;left: 10px;bottom: 5px;">
          <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="addbtn()">新增股票</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="CompanyTable" border style="width: 100%;min-height: 78%;max-height: 78%;overflow: auto;">
      <el-table-column resizable prop="stocks_id" label="id" width="60" align="center">
      </el-table-column>
      <el-table-column resizable prop="sort" label="排序" width="auto" min-width="100px" align="center">
      </el-table-column>
      <el-table-column resizable prop="Stocks" label="股票名称" width="auto" min-width="200px" align="center">
      </el-table-column>

      <el-table-column resizable prop="Price_Movement" label="价格变动情况" width="auto" min-width="200px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px;height:20px" :src="'' + scope.row.Price_Movement"
            :preview-src-list="['' + scope.row.Price_Movement]">
            <div slot="error" class="image-slot" style="width: 50px;">
              <div style="width: 50px;">{{ scope.row.Price_Movement == '' ? '加载失败' : '空图片或者地址错误' }}</div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="Current_Price" label="当前价格" width="auto" min-width="120px" align="center">
      </el-table-column>
      <el-table-column resizable prop="Joining_Date" label="加入日期" width="auto" min-width="170px" align="center">
      </el-table-column>
      <el-table-column resizable prop="HPY_Since_Joining_Date" label="自加入日期持有期收益率" width="auto" min-width="170px"
        align="center">
      </el-table-column>
      <el-table-column resizable prop="Est__Return" label="预计回报" width="auto" min-width="120px" align="center">
      </el-table-column>
      <el-table-column resizable prop="introduction_zh_tw" label="简介 繁体中文" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="introduction_zh_cn" label="简介 简体中文" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="introduction_en" label="简介 英文" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="introduction_ja" label="简介 日语" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="introduction_ko" label="简介 韩语" width="auto" min-width="200px" align="center">
      </el-table-column>

      <el-table-column resizable prop="Est__Max_Drawdown" label="预计最大回撤" width="auto" min-width="120px" align="center">
      </el-table-column>
      <el-table-column resizable prop="Weight" label="权重" width="auto" min-width="100px" align="center">
      </el-table-column>
      <el-table-column resizable prop="add_time" label="添加时间" width="auto" min-width="170px" align="center">
      </el-table-column>

      <el-table-column resizable label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button @click="tableEditing(scope.row)" type="primary" plain size="small">编辑</el-button>
          <el-button @click="del_stockDeletion(scope.row.stocks_id)" type="danger" plain size="small">刪除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="text-align: right; margin-top: 5px;">
      <el-pagination background layout="prev, pager, next,total" :total="total" :page-size="pagesize"
        @current-change="current_change"></el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="titles" :visible.sync="dialogVisible" width="95%"
      @close="handleClose" top="5vh">
      <div class="pop-up-form">
        <div style="display: flex;justify-content: center;width: 95%;margin: 8px 0;">
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">选择语言：</span>
            <el-select style="flex: 6;" v-model="selectedLanguage" placeholder="选择语言" @change="handleLanguageChange">
              <el-option v-for="item in languages" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

          </div>
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">股票名称：</span>
            <el-input style="flex: 6;" v-model="addform.Stocks"></el-input>

          </div>
          <div style="display: flex;flex: 1;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">当前价格：</span>
            <el-input style="flex: 6;" v-model="addform.Current_Price"></el-input>
          </div>
        </div>

        <div style="display: flex;justify-content: center;width: 95%;margin: 8px 0;">
          <div style="display: flex;flex: 1;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">加入日期：</span>
            <el-date-picker style="flex: 6;" v-model="addform.Joining_Date" type="datetime" placeholder="请选择添加时间"
              :format="'yyyy-MM-dd HH:mm:ss'" :value-format="'yyyy-MM-dd HH:mm:ss'">
            </el-date-picker>
          </div>
          <div style="flex: 1;display: flex;">
            <span
              style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 12px;">加入日期以来收益率：</span>
            <el-input style="flex: 6;" v-model="addform.HPY_Since_Joining_Date"></el-input>
          </div>
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">权重：</span>
            <el-input style="flex: 6;" v-model="addform.Weight"></el-input>
          </div>
        </div>

        <div style="display: flex;justify-content: center;width: 95%;margin: 8px 0;">
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">预计回报：</span>
            <el-input style="flex: 6;" v-model="addform.Est__Return"></el-input>
          </div>
          <div style="display: flex;flex: 1;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">预计最大回撤：</span>
            <el-input style="flex: 6;" v-model="addform.Est__Max_Drawdown"></el-input>
          </div>
          <div style="display: flex;flex: 1;">
            <span
              style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 12px;max-width: 200px;">价格变动图表：</span>
            <input style="flex: 6;line-height: 40px;margin-left:0" type="file" ref="fileInput1" id="roleHeadgear"
              accept="image/*" @change="handleFileChange" required />
          </div>
        </div>
        <div style="display: flex;justify-content: center;width: 95%;margin: 8px 0;">
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">简介：</span>
            <el-input style="flex:6;" v-model="addform.introduction"></el-input>
          </div>
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">爬虫链接：</span>
            <el-input style="flex: 6;" v-model="addform.crawler_link"></el-input>
          </div>
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">序号：</span>
            <el-input style="flex: 6;" v-model="addform.sort"></el-input>
          </div>
        </div>

        <div style="display: flex;justify-content: center;width: 95%;margin: 8px 0;">
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">操作建议来源：</span>
            <el-input style="flex:6;" v-model="addform.operation_source"></el-input>
          </div>
          <div style="flex: 1;display: flex;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">出售价格：</span>
            <el-input style="flex: 6;" v-model="addform.sell_price"></el-input>
          </div>
          <div style="flex: 1;display: flex;">

          </div>
        </div>
        <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="sfzqqa" style="z-index: 1;">
          <el-tab-pane label="内容" name="1">
            <div style="border: 1px solid #ccc;height:auto;z-index: 999;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor1" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: calc(100vh - 200px - 5vh - 54px - 120px - 40px); overflow-y: hidden;" v-model="html1"
                :defaultConfig="editorConfig1" :mode="mode" @onCreated="onCreated1" @customAlert="customAlert1" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="Income related" name="2">
            <div style="border: 1px solid #ccc;height:auto;z-index: 999;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor2" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: calc(100vh - 200px - 5vh - 54px - 120px - 40px); overflow-y: hidden;" v-model="html2"
                :defaultConfig="editorConfig2" :mode="mode" @onCreated="onCreated2" @customAlert="customAlert2" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="Cash Flow related" name="3">
            <div style="border: 1px solid #ccc;height:auto;z-index: 999;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor3" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: calc(100vh - 200px - 5vh - 54px - 120px - 40px); overflow-y: hidden;" v-model="html3"
                :defaultConfig="editorConfig3" :mode="mode" @onCreated="onCreated3" @customAlert="customAlert3" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="Asset related" name="4">
            <div style="border: 1px solid #ccc;height:auto;z-index: 999;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor4" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: calc(100vh - 200px - 5vh - 54px - 120px - 40px); overflow-y: hidden;" v-model="html4"
                :defaultConfig="editorConfig4" :mode="mode" @onCreated="onCreated4" @customAlert="customAlert4" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button v-show="titles == '新增'" type="primary" @click="add_stockAddition()" size="small">确
          定</el-button>
        <el-button v-show="titles == '编辑'" type="primary" @click="upd_stockEditor()" size="small">更
          新</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { stockList, stockAddition, stockEditor, stockDeletion } from "@/utils/api";
export default {
  name: 'CompanyInfo',
  components: { Editor, Toolbar },
  data() {
    return {
      // 富文本
      editor1: null, // 富文本实例对象
      editor2: null, // 富文本实例对象
      editor3: null, // 富文本实例对象
      editor4: null, // 富文本实例对象
      html1: '', // 富文本初始html
      html2: '', // 富文本初始html
      html3: '', // 富文本初始html
      html4: '', // 富文本初始html
      toolbarConfig: {
        excludeKeys: [
          'group-video'
        ],
      },
      isVisible: false,
      editorConfig1: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: '/admin/System/imgUpload', // 上传图片的地址
            fieldName: 'image', // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              'token': localStorage.getItem('token'), // 将 token 添加在请求头中
            },
            allowedFileTypes: ['image/*'], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log('图片上传成功', res, file)
              alert(res.msg)
            },
            onFailed(file, res) {
              console.log(res, file, '失败');
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert: (res, insertFn) => {
              insertFn('' + res.data[0]);
            },
          }
        },

      },
      editorConfig2: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: '/admin/System/imgUpload', // 上传图片的地址
            fieldName: 'image', // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              'token': localStorage.getItem('token'), // 将 token 添加在请求头中
            },
            allowedFileTypes: ['image/*'], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log('图片上传成功', res, file)
              alert(res.msg)
            },
            onFailed(file, res) {
              console.log(res, file, '失败');
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert: (res, insertFn) => {
              insertFn('' + res.data[0]);
            },
          }
        },

      },
      editorConfig3: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: '/admin/System/imgUpload', // 上传图片的地址
            fieldName: 'image', // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              'token': localStorage.getItem('token'), // 将 token 添加在请求头中
            },
            allowedFileTypes: ['image/*'], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log('图片上传成功', res, file)
              alert(res.msg)
            },
            onFailed(file, res) {
              console.log(res, file, '失败');
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert: (res, insertFn) => {
              insertFn('' + res.data[0]);
            },
          }
        },

      },
      editorConfig4: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: '/admin/System/imgUpload', // 上传图片的地址
            fieldName: 'image', // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              'token': localStorage.getItem('token'), // 将 token 添加在请求头中
            },
            allowedFileTypes: ['image/*'], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log('图片上传成功', res, file)
              alert(res.msg)
            },
            onFailed(file, res) {
              console.log(res, file, '失败');
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert: (res, insertFn) => {
              insertFn('' + res.data[0]);
            },
          }
        },

      },
      mode: 'default', // or 'simple'
      addform: {
        Stocks: '',
        Current_Price: '',
        Joining_Date: '',
        HPY_Since_Joining_Date: '',
        Est__Return: '',
        Est__Max_Drawdown: '',
        Weight: '',
        introduction: '',
        crawler_link: '',
        sort: '',
        operation_source: '',
        sell_price: '',
      },
      CompanyTable: [],
      enableData: [{
        value: 0,
        label: '未使用'
      }, {
        value: 1,
        label: '已使用'
      }],
      dialogVisible: false,
      total: 100, //总条数
      pagesize: 10, //指定展示多少条
      currentPage: 1, //当前页码
      titles: '',
      roleHeadgear: null,
      activeTab: '1',
      selectedLanguage: "", // 当前选择的语言
      languages: [
        { value: "content_en", label: "英语" },
        { value: "content_ja", label: "日语" },
        { value: "content_ko", label: "韩语" },
        { value: "content_zh_tw", label: "繁体中文" },
        { value: "content_zh_cn", label: "简体中文" },

      ],
    };
  },
  mounted() {
    this.get_stockList()
  },

  methods: {
    // Tab 切换时触发
    handleTabChange() {
      // alert(11)
      // this.editor1.setHtml('')
    },
    handleFileChange(event) {
      this.roleHeadgear = event.target.files[0];
      if (this.roleHeadgear) {
        this.$message.success('上传成功')
      }
    },
    // 查询公司列表
    async get_stockList() {
      let data = {}
      data.page = this.currentPage
      const res = await stockList(data).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);
        this.CompanyTable = res.data.data.data
        this.total = res.data.data.total
      } else {
        this.$message.error(res.data.message);
      }
    },
    handleLanguageChange(value) {
      // 回调函数，在选择语言后触发
      console.log('选择的语言:', value);
      if (this.titles === '编辑') {
        // 映射语言字段，减少冗余代码
        const languageMap = {
          content_ja: 'ja',
          content_ko: 'ko',
          content_en: 'en',
          content_zh_tw: 'zh_tw',
          content_zh_cn: 'zh_cn',
        };



        // 获取语言后缀（例如：'ja'、'ko'、'en'、'zh_tw'）
        const langSuffix = languageMap[value];

        this.addform.introduction = this.row[`introduction_${langSuffix}`] || ''

        this.$nextTick(() => {
          const waitForEditor1 = () => {
            try {
              if (this.editor1) {
                console.log(this.editor1.setHtml, 'this.editor1.setHtml');
                // 当 this.editor 有值时执行逻辑
                console.log('1Editor 已初始化，执行 setHtml');
                this.editor1.setHtml(this.row[`content_${langSuffix}`] || '');
                console.log(this.editor1.setHtml, 'setHtml完成，已设置内容');
              } else {
                // 如果 this.editor 为空，继续等待
                console.log(this.editor1, '等待 Editor 初始化...');
                setTimeout(waitForEditor1, 100); // 每隔 100ms 检查一次
              }
            } catch (error) {
              // 捕获异常，避免影响体验并继续尝试执行
              console.error('执行出错，继续等待 Editor 初始化...', error);
              setTimeout(waitForEditor1, 100); // 如果发生错误，继续等待
            }
          }

          waitForEditor1();
        });

        this.$nextTick(() => {
          const waitForEditor2 = () => {
            try {
              if (this.editor2) {
                console.log(this.editor2.setHtml, 'this.editor2.setHtml');
                // 当 this.editor 有值时执行逻辑
                console.log('1Editor 已初始化，执行 setHtml');
                this.editor2.setHtml(this.row[`Income_related_${langSuffix}`] || '');
                console.log(this.editor2.setHtml, 'setHtml完成，已设置内容');
              } else {
                // 如果 this.editor 为空，继续等待
                console.log(this.editor2, '等待 Editor 初始化...');
                setTimeout(waitForEditor2, 100); // 每隔 100ms 检查一次
              }
            } catch (error) {
              // 捕获异常，避免影响体验并继续尝试执行
              console.error('执行出错，继续等待 Editor 初始化...', error);
              setTimeout(waitForEditor2, 100); // 如果发生错误，继续等待
            }
          }

          waitForEditor2();
        });

        this.$nextTick(() => {
          const waitForEditor3 = () => {
            try {
              if (this.editor3) {
                console.log(this.editor3.setHtml, 'this.editor3.setHtml');
                // 当 this.editor 有值时执行逻辑
                console.log('1Editor 已初始化，执行 setHtml');
                this.editor3.setHtml(this.row[`Cash_Flow_relatedt_${langSuffix}`] || '');
                console.log(this.editor3.setHtml, 'setHtml完成，已设置内容');
              } else {
                // 如果 this.editor 为空，继续等待
                console.log(this.editor3, '等待 Editor 初始化...');
                setTimeout(waitForEditor3, 100); // 每隔 100ms 检查一次
              }
            } catch (error) {
              // 捕获异常，避免影响体验并继续尝试执行
              console.error('执行出错，继续等待 Editor 初始化...', error);
              setTimeout(waitForEditor3, 100); // 如果发生错误，继续等待
            }
          }

          waitForEditor3();
        });

        this.$nextTick(() => {
          const waitForEditor4 = () => {
            try {
              if (this.editor4) {
                console.log(this.editor4.setHtml, 'this.editor4.setHtml');
                // 当 this.editor 有值时执行逻辑
                console.log('1Editor 已初始化，执行 setHtml');
                this.editor4.setHtml(this.row[`Asset_related_${langSuffix}`] || '');
                console.log(this.editor4.setHtml, 'setHtml完成，已设置内容');
              } else {
                // 如果 this.editor 为空，继续等待
                console.log(this.editor4, '等待 Editor 初始化...');
                setTimeout(waitForEditor4, 100); // 每隔 100ms 检查一次
              }
            } catch (error) {
              // 捕获异常，避免影响体验并继续尝试执行
              console.error('执行出错，继续等待 Editor 初始化...', error);
              setTimeout(waitForEditor4, 100); // 如果发生错误，继续等待
            }
          }

          waitForEditor4();
        });

        // this.editor1.setHtml(this.row[`content_${value}`] || '');
        // this.editor2.setHtml(this.row[`Income_related_${value}`] || '');
        // this.editor3.setHtml(this.row[`Cash_Flow_relatedt_${value}`] || '');
        // this.editor4.setHtml(this.row[`Asset_related_${value}`] || '');


      }
    },
    // 新增公司
    async add_stockAddition() {
      // 检查语言是否已选择
      if (!this.selectedLanguage) {
        this.$message.info('请选择语言');
        return;
      }
      let data = new FormData();
      const fields = {
        'Stocks': this.addform.Stocks,
        'Current_Price': this.addform.Current_Price,
        'Joining_Date': this.addform.Joining_Date,
        'HPY_Since_Joining_Date': this.addform.HPY_Since_Joining_Date,
        'Est__Return': this.addform.Est__Return,
        'Est__Max_Drawdown': this.addform.Est__Max_Drawdown,
        'Weight': this.addform.Weight,
        'crawler_link': this.addform.crawler_link,
        'sort': this.addform.sort,
        'operation_source': this.addform.operation_source,
        'sell_price': this.addform.sell_price,

      };

      // 遍历对象并只添加有效字段
      Object.entries(fields).forEach(([key, value]) => {
        // 判断字段值是否为空、null或undefined
        if (value !== undefined && value !== null && value !== '') {
          data.append(key, value);
        }
      });

      if (this.roleHeadgear) {
        data.append('Price_Movement', this.roleHeadgear);
      }


      // 映射语言字段，减少冗余代码
      const languageMap = {
        content_ja: 'ja',
        content_ko: 'ko',
        content_en: 'en',
        content_zh_tw: 'zh_tw',
        content_zh_cn: 'zh_cn',
      };

      // 获取语言后缀（例如：'ja'、'ko'、'en'、'zh_tw'）
      const langSuffix = languageMap[this.selectedLanguage];

      // 检查是否找到对应的语言后缀
      if (langSuffix) {
        // 拼装字段名并添加到 FormData
        data.append(`content_${langSuffix}`, this.editor1.getHtml());
        data.append(`Income_related_${langSuffix}`, this.editor2.getHtml());
        data.append(`Cash_Flow_related_${langSuffix}`, this.editor3.getHtml());
        data.append(`Asset_related_${langSuffix}`, this.editor4.getHtml());
        if (this.addform.introduction) {
          data.append(`introduction_${langSuffix}`, this.addform.introduction);
        }


      } else {
        this.$message.info('语言字段不存在');
      }



      const res = await stockAddition(data).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);
        this.get_stockList()
        this.$refs.fileInput1.value = null;
        this.dialogVisible = false
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 更新公司
    async upd_stockEditor() {

      let data = new FormData();
      const fields = {
        'Stocks': this.addform.Stocks,
        'Current_Price': this.addform.Current_Price,
        'Joining_Date': this.addform.Joining_Date,
        'HPY_Since_Joining_Date': this.addform.HPY_Since_Joining_Date,
        'Est__Return': this.addform.Est__Return,
        'stocks_id': this.addform.id,
        'Est__Max_Drawdown': this.addform.Est__Max_Drawdown,
        'Weight': this.addform.Weight,
        'crawler_link': this.addform.crawler_link,
        'sort': this.addform.sort,
        'operation_source': this.addform.operation_source,
        'sell_price': this.addform.sell_price,


      };

      // 遍历对象并只添加有效字段
      Object.entries(fields).forEach(([key, value]) => {
        // 判断字段值是否为空、null或undefined
        if (value !== undefined && value !== null && value !== '') {
          data.append(key, value);
        }
      });

      if (this.roleHeadgear) {
        data.append('Price_Movement', this.roleHeadgear);
      }
      // 映射语言字段，减少冗余代码
      const languageMap = {
        content_ja: 'ja',
        content_ko: 'ko',
        content_en: 'en',
        content_zh_tw: 'zh_tw',
        content_zh_cn: 'zh_cn',
      };

      // 获取语言后缀（例如：'ja'、'ko'、'en'、'zh_tw'）
      const langSuffix = languageMap[this.selectedLanguage];

      // 检查是否找到对应的语言后缀
      if (langSuffix) {
        // 拼装字段名并添加到 FormData
        data.append(`content_${langSuffix}`, this.editor1.getHtml());
        data.append(`Income_related_${langSuffix}`, this.editor2.getHtml());
        data.append(`Cash_Flow_related_${langSuffix}`, this.editor3.getHtml());
        data.append(`Asset_related_${langSuffix}`, this.editor4.getHtml());
        if (this.addform.introduction) {
          data.append(`introduction_${langSuffix}`, this.addform.introduction);
        }

      } else {
        this.$message.info('语言字段不存在');
      }

      const res = await stockEditor(data, this.addform.id).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);
        this.dialogVisible = false
        this.get_stockList()
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 刪除公司
    async del_stockDeletion(id) {
      try {
        await this.$confirm("是否继续执行操作？", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        });

        let data = { stocks_id: id };
        const res = await stockDeletion(data).catch((err) => {
          return console.error(err);
        });

        if (res && res.status == "200") {
          this.$message.success(res.data.message);
          this.dialogVisible = false;
          this.get_stockList();
        } else {
          this.$message.error(res.data.message);
        }
      } catch (error) {
        // 用户点击取消或关闭对话框
        console.error(error);
      }
    },
    // 关闭弹窗时
    handleClose() {
      this.addform = {
        Stocks: '',
        Current_Price: '',
        Joining_Date: '',
        HPY_Since_Joining_Date: '',
        Est__Return: '',
        Est__Max_Drawdown: '',
        Weight: '',
        introduction: '',
        crawler_link: '',
        sort: '',
        operation_source: '',
        sell_price: '',

      }
      this.$refs.fileInput1.value = null;
      // this.html1 = '<p>默认文字，请删除。</p>'
      // this.html2 = '<p>默认文字，请删除。</p>'
      // this.html3 = '<p>默认文字，请删除。</p>'
      // this.html4 = '<p>默认文字，请删除。</p>'
      this.editor1.setHtml('');
      this.editor2.setHtml('');
      this.editor3.setHtml('');
      this.editor4.setHtml('');
    },
    handleClosetable() {

    },
    // 分页
    current_change(currentPage) {
      this.currentPage = currentPage;
      this.get_stockList();
    },
    // 重置
    resetForm() {
      this.form = {
        name: ''
      }
      this.currentPage = 1
      this.get_stockList();
    },
    // 编辑打开时
    tableEditing(row) {

      console.log(row.content_en, 'row.content_en');
      this.titles = '编辑'
      this.dialogVisible = true
      this.row = row
      const isTrue = (value) => {
        if (value == null || value == undefined || value === "null" || value === "undefined") {
          return false;
        }
        return true;
      };
      if (isTrue(row.Stocks)) {
        this.addform.Stocks = row.Stocks
      }
      if (isTrue(row.Current_Price)) {
        this.addform.Current_Price = row.Current_Price
      }
      if (isTrue(row.Joining_Date)) {
        this.addform.Joining_Date = row.Joining_Date
      }
      if (isTrue(row.HPY_Since_Joining_Date)) {
        this.addform.HPY_Since_Joining_Date = row.HPY_Since_Joining_Date
      }
      if (isTrue(row.Est__Return)) {
        this.addform.Est__Return = row.Est__Return
      }
      if (isTrue(row.Est__Max_Drawdown)) {
        this.addform.Est__Max_Drawdown = row.Est__Max_Drawdown
      }
      if (isTrue(row.Weight)) {
        this.addform.Weight = row.Weight
      }
      if (isTrue(row.introduction_en)) {
        this.addform.introduction = row.introduction_en
      }
      if (isTrue(row.crawler_link)) {
        this.addform.crawler_link = row.crawler_link
      }
      if (isTrue(row.sort)) {
        this.addform.sort = row.sort
      }

      if (isTrue(row.operation_source)) {
        this.addform.operation_source = row.operation_source
      }

      if (isTrue(row.sell_price)) {
        this.addform.sell_price = row.sell_price
      }
      this.addform.id = row.stocks_id

      this.selectedLanguage = 'content_en'
      // setTimeout(() => {
      //   this.editor1.setHtml(row.content_en || '');
      //   this.editor2.setHtml(row.Income_related_en || '');
      //   this.editor3.setHtml(row.Cash_Flow_related_en || '');
      //   this.editor4.setHtml(row.Asset_related_en || '');
      // }, 0);




      this.$nextTick(() => {
        const waitForEditor1 = () => {
          try {
            if (this.editor1) {
              console.log(this.editor1.setHtml, 'this.editor1.setHtml');
              // 当 this.editor 有值时执行逻辑
              console.log('1Editor 已初始化，执行 setHtml');
              this.editor1.setHtml(row.content_en || '');
              console.log(this.editor1.setHtml, 'setHtml完成，已设置内容');
            } else {
              // 如果 this.editor 为空，继续等待
              console.log(this.editor1, '等待 Editor 初始化...');
              setTimeout(waitForEditor1, 100); // 每隔 100ms 检查一次
            }
          } catch (error) {
            // 捕获异常，避免影响体验并继续尝试执行
            console.error('执行出错，继续等待 Editor 初始化...', error);
            setTimeout(waitForEditor1, 100); // 如果发生错误，继续等待
          }
        }

        waitForEditor1();
      });

      this.$nextTick(() => {
        const waitForEditor2 = () => {
          try {
            if (this.editor2) {
              console.log(this.editor2.setHtml, 'this.editor2.setHtml');
              // 当 this.editor 有值时执行逻辑
              console.log('1Editor 已初始化，执行 setHtml');
              this.editor2.setHtml(row.Income_related_en || '');
              console.log(this.editor2.setHtml, 'setHtml完成，已设置内容');
            } else {
              // 如果 this.editor 为空，继续等待
              console.log(this.editor2, '等待 Editor 初始化...');
              setTimeout(waitForEditor2, 100); // 每隔 100ms 检查一次
            }
          } catch (error) {
            // 捕获异常，避免影响体验并继续尝试执行
            console.error('执行出错，继续等待 Editor 初始化...', error);
            setTimeout(waitForEditor2, 100); // 如果发生错误，继续等待
          }
        }

        waitForEditor2();
      });

      this.$nextTick(() => {
        const waitForEditor3 = () => {
          try {
            if (this.editor3) {
              console.log(this.editor3.setHtml, 'this.editor3.setHtml');
              // 当 this.editor 有值时执行逻辑
              console.log('1Editor 已初始化，执行 setHtml');
              this.editor3.setHtml(row.Cash_Flow_related_en || '');
              console.log(this.editor3.setHtml, 'setHtml完成，已设置内容');
            } else {
              // 如果 this.editor 为空，继续等待
              console.log(this.editor3, '等待 Editor 初始化...');
              setTimeout(waitForEditor3, 100); // 每隔 100ms 检查一次
            }
          } catch (error) {
            // 捕获异常，避免影响体验并继续尝试执行
            console.error('执行出错，继续等待 Editor 初始化...', error);
            setTimeout(waitForEditor3, 100); // 如果发生错误，继续等待
          }
        }

        waitForEditor3();
      });

      this.$nextTick(() => {
        const waitForEditor4 = () => {
          try {
            if (this.editor4) {
              console.log(this.editor4.setHtml, 'this.editor4.setHtml');
              // 当 this.editor 有值时执行逻辑
              console.log('1Editor 已初始化，执行 setHtml');
              this.editor4.setHtml(row.Asset_related_en || '');
              console.log(this.editor4.setHtml, 'setHtml完成，已设置内容');
            } else {
              // 如果 this.editor 为空，继续等待
              console.log(this.editor4, '等待 Editor 初始化...');
              setTimeout(waitForEditor4, 100); // 每隔 100ms 检查一次
            }
          } catch (error) {
            // 捕获异常，避免影响体验并继续尝试执行
            console.error('执行出错，继续等待 Editor 初始化...', error);
            setTimeout(waitForEditor4, 100); // 如果发生错误，继续等待
          }
        }

        waitForEditor4();
      });


    },
    // 新增打开时
    addbtn() {
      this.dialogVisible = true;
      this.titles = '新增'
    },
    // 富文本
    onCreated1(editor) {
      this.editor1 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onCreated2(editor) {
      this.editor2 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onCreated3(editor) {
      this.editor3 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onCreated4(editor) {
      this.editor4 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    // 组件销毁时销毁编辑器
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy()
    },
    customAlert1(info, type) { window.alert(`customAlert in Vue demo\n${type}:\n${info}`) },
    customAlert2(info, type) { window.alert(`customAlert in Vue demo\n${type}:\n${info}`) },
    customAlert3(info, type) { window.alert(`customAlert in Vue demo\n${type}:\n${info}`) },
    customAlert4(info, type) { window.alert(`customAlert in Vue demo\n${type}:\n${info}`) },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less">
.cell {
  font-size: 12px;
  white-space: nowrap !important;
}

.el-dialog__body {
  padding: 0 10px !important;
}

.demo-table-expand {
  font-size: 0;
  margin-left: 10px;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.sfzqqa {
  .el-tabs__nav-scroll {
    display: flex;
    justify-content: center;
  }
}
</style>
<style lang="less" scoped>
.DealerInfoStyle {
  width: 100%;
  padding: 0 10px;
  // background-color: aquamarine;
  height: calc(100vh - 100px);
  // border: 1px #000 solid;

  .cardAdmin {
    position: relative;
    // height: 18%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 0;

    border: #ebeef5 solid 1px;
    padding: 0 5px;
    margin-bottom: 2px;


    .formContainer {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      padding: 0;
      align-self: baseline;
      padding-bottom: 40px;
    }

    .formSearch {
      width: 25%;
      min-width: 25%;
      margin: 10px 0;
      height: 40px;
      display: flex;
      justify-content: center;
    }
  }

  .pop-up-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 0;
    align-self: baseline;
    margin: 10px 0;
    justify-content: center;
    padding-right: 15px;

    .form-options {
      width: 100%;
      min-width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }
}
</style>
